<template>
  <div class="aritle-list">
    <van-pull-refresh
      v-model="refreshLoading"
      success-text="刷新成功"
      @refresh="getNextPageArticle"
    >
      <van-list
        v-model="loading"
        @load="getNextPageArticle"
        :immediate-check="false"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <article-item
          v-for="item in articles"
          :aritcle-info="item"
          :key="item.art_id"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticlesAPI } from "@/api";

import ArticleItem from "./ArticleItem";

export default {
  name: "ArticleList",
  props: {
    channelId: [Number, String],
  },

  components: {
    ArticleItem,
  },

  data() {
    return {
      articles: [],
      preTimestamp: "",
      loading: false,
      finished: false,
      error: false,

      refreshLoading: false,
    };
  },

  created() {
    this.getFirstPageArticle();
  },

  methods: {
    async getFirstPageArticle() {
      try {
        const { data } = await getArticlesAPI(this.channelId, +new Date());
        // console.log(data);

        this.articles = data.data.results;

        this.preTimestamp = data.data.pre_timestamp;
      } catch (error) {
        // 如果axios的错误 状态码400
        if (error.response?.status === 400) {
          this.$toast.fail(error.response.data.message);
        } else {
          throw error; //如果是500或者js的错误
        }
      }
    },

    async getNextPageArticle() {
      //   console.log('9999')
      try {
        //发送请求
        const { data } = await getArticlesAPI(
          this.channelId,
          this.preTimestamp
        );

        //添加数据
        const results = data.data.results;
        //this.articles.push(...results)

        // this.articles = [...this.articles, ...results]
        if (this.loading) {
          this.articles = [...this.articles, ...results];
        } else {
          this.articles = [...results, ...this.articles];
        }

        //更新事件龊

        this.preTimestamp = data.data.pre_timestamp;

        //判断是否加载完毕
        if (data.data.pre_timestamp === null) {
          this.finished = true;
        }
        // this.loading = false
      } catch (error) {
        this.error = true;
      } finally {
        this.loading = false;
        this.refreshLoading = false;
      }
    },
  },
};
</script>

<style scoped lang="less">
.aritle-list {
  height: calc(100vh - 100px - 92px - 83px);
  overflow: auto;
}
</style>